module transmit(input rateen, clk, rst, iocs, iorw, 
			input [7:0] data, input [1:0] ioaddr, 
			output tbr, txd);

	reg [8:0] tsr;
	reg [7:0] buff;
	reg [3:0] shiftcnt;
	reg datawaiting;
	always @(posedge clk) begin
		if (rst)
			buff <= 8'd0;
		else begin
			if (iocs & ~iorw & (ioaddr == 2'd0))
				buff <= data;
		end
	end

	always @(posedge clk) begin
		if (rst)
			tsr <= 9'b111111111;
		else begin
			if(rateen) begin
				if(shiftcnt == 4'd9 & datawaiting)		
					tsr <= {buff, 1'b0};
				else
					tsr <= {1'b1, tsr[8:1]};
			end
		end
	end

	always @(posedge clk) begin
		if(rst)
			shiftcnt <= 4'd9;
		else begin 
			if(rateen) begin
				if (shiftcnt == 4'd9 & datawaiting)
					shiftcnt <= 4'd0;
				else if (shiftcnt != 4'd9)
					shiftcnt <= shiftcnt + 1;
			end
		end
	end

	always @(posedge clk) begin
		if(rst)
			datawaiting <= 1'b0;
		else if (rateen & (shiftcnt == 4'd9))	//if nine bits have been shifted out
			datawaiting <= 1'b0;
		else	if (iocs & ~iorw & (ioaddr == 2'b0))
			datawaiting <= 1'b1;		
	end


	assign txd = tsr[0];
	assign tbr = ~datawaiting;
endmodule
